package com.zwq.gateway.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 设置白名单过滤器
 */
@Configuration
public class WhitelistGlobalFilter implements GlobalFilter {
    private static final Logger log = LoggerFactory.getLogger(WhitelistGlobalFilter.class);
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        // 记录开始时间
        long startTime = System.currentTimeMillis();
        exchange.getAttributes().put("startTime", startTime);

        // 继续执行后续过滤器
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            // 计算并输出请求时长
            long endTime = System.currentTimeMillis();
            long duration = endTime - startTime;
            log.info("Request completed in " + duration + "ms");
        }));

    }
}
